package server;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;

public class ImageToolkit {

	private final static Rectangle r = new Rectangle(Toolkit
			.getDefaultToolkit().getScreenSize());

	public static BufferedImage scaleImage(Image image, int width, int height,
			boolean isNyditot) {
		int imageWidth = image.getWidth(null);
		int imageHeight = image.getHeight(null);
		if (isNyditot) {
			int tmp = height;
			height = width;
			width = tmp;
		}
		float scale = getRatio(imageWidth, imageHeight, width, height);
		imageWidth = (int) (scale * imageWidth);
		imageHeight = (int) (scale * imageHeight);
		image = image.getScaledInstance(imageWidth, imageHeight,
				Image.SCALE_AREA_AVERAGING);
		BufferedImage mBufferedImage = null;
		Graphics2D g2 = null;
		if (isNyditot) {
			mBufferedImage = new BufferedImage(imageHeight, imageWidth,
					BufferedImage.TYPE_INT_RGB);
			g2 = mBufferedImage.createGraphics();
			g2.rotate(1.57, imageHeight / 2, imageHeight / 2);
		} else {
			mBufferedImage = new BufferedImage(imageWidth, imageHeight,
					BufferedImage.TYPE_INT_RGB);
			g2 = mBufferedImage.createGraphics();
		}
		g2.drawImage(image, 0, 0, imageWidth, imageHeight, Color.white, null);
		g2.dispose();
		float[] kernelData2 = { -0.125f, -0.125f, -0.125f, -0.125f, 2, -0.125f,
				-0.125f, -0.125f, -0.125f };
		Kernel kernel = new Kernel(3, 3, kernelData2);
		ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
		mBufferedImage = cOp.filter(mBufferedImage, null);

		return mBufferedImage;
	}

	public static BufferedImage captureScreen(Rectangle rt) {
		BufferedImage screen = null;
		try {
			Robot robot = new Robot();
			screen = robot.createScreenCapture(rt);
			if (screen == null) {
				System.out.print("fail to capture the screen!");
				return null;
			}
		} catch (AWTException e) {
			e.printStackTrace();
		}
		return screen;
	}

	private static float getRatio(int width, int height, int maxWidth,
			int maxHeight) {
		float Ratio = 1.0f;
		float widthRatio;
		float heightRatio;
		widthRatio = (float) maxWidth / width;
		heightRatio = (float) maxHeight / height;
		if (widthRatio < 1.0 || heightRatio < 1.0) {
			Ratio = widthRatio <= heightRatio ? widthRatio : heightRatio;
		}
		return Ratio;
	}

	public static BufferedImage scaledScreen(int width, int height,
			boolean isNyditot) {
		return scaleImage(captureScreen(r), width, height, isNyditot);
	}
}
